package models

import (
	"diancan/dao"
	"diancan/logUtlis"
	"fmt"
)

type MenuList struct {
   Name string `json:"name" gorm:"column:name"`
   Title string `json:"title" gorm:"column:title"`
   Counts int `json:"counts"`
   OneMenuListFK int `json:"one_menu_list_fk" gorm:"column:oneMenuListFK"`
   StoreName string `json:"store_name" gorm:"column:name"`
   EveryDay string `json:"every_day" gorm:"column:everyDay"`
   TwoMenu []TwoMenuList `json:"two_menu" gorm:"column:twoMenu"`
}

type TwoMenuList struct {
	Twolistimgurl string `json:"twolistimgurl" gorm:"column:twoListImgUrl"`
	DishName string `json:"dishName" gorm:"column:dishName"`
	Price float32 `json:"price" gorm:"column:price"`
	EveryDay int `json:"every_day" gorm:"column:everyDay"`
}

func QueryMenuList() (mMenuList []MenuList,err error)  {

		//查询店名
		var storeName MenuList
		strSqlName:= `select name,everyDay from storeName`
		err = dao.DB.Raw(strSqlName).Scan(&storeName).Error
		if err != nil {
			logUtlis.MainLog.Error("查询店名出错："+err.Error())
		}


		strSql:= `select   tML.oneMenuListFK,
					   one.name,
					   one.title,
					   count(*) as 'counts'
				from
					 oneMenuList one join twoMenuList tML
						 on one.id = tML.oneMenuListFK
				group by one.id`

		var mMenuLists []MenuList

		err = dao.DB.Raw(strSql).Scan(&mMenuLists).Error
		if err != nil {
			logUtlis.MainLog.Error("分组查询出错："+err.Error())
			return nil, err
		}

		var mTwoMenuList []TwoMenuList

		var mRetMenuList = make([]MenuList,0)

		for _,v:=range mMenuLists{
			fk := v.OneMenuListFK
			strSql:=`select twoListImgUrl,dishName,price,everyDay from twoMenuList where oneMenuListFK = ? `
			err := dao.DB.Raw(strSql, fk).Scan(&mTwoMenuList).Error
			if err != nil {
				logUtlis.MainLog.Error("查询数据库出错:"+err.Error())
				return nil, err
				break
			}
			var sumTwoMenuList = make([]TwoMenuList,0)
			for _,v:=range mTwoMenuList{
				sprintf := fmt.Sprintf("%s%s%s%s%s",
					"http://",
					dao.ViperConfig.GetString("mysql.path"), ":", dao.ViperConfig.GetString("router.port"), v.Twolistimgurl)
				v.Twolistimgurl= sprintf
				sumTwoMenuList = append(sumTwoMenuList,v)
			}

			mRetMenuList = append(mRetMenuList, MenuList{
				Name:          v.Name,
				Title:         v.Title,
				Counts:        v.Counts,
				OneMenuListFK: v.OneMenuListFK,
				StoreName: storeName.Name,
				EveryDay: storeName.EveryDay,
				TwoMenu:       sumTwoMenuList,
			})
		}



		return mRetMenuList,nil

}
